/*
 * Copyright (c) 2006 Hyperic, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.hyperic.sigar.*;
import java.text.DecimalFormat;

/*

Example to show the process state for a given pid.

Compile the example:
% javac -classpath sigar-bin/lib/sigar.jar ProcessState.java

State of the java process running the example:
% java -classpath sigar-bin/lib/sigar.jar:. ProcessState
java: Running

State of the bash shell when invoking the example is running:
% java -classpath sigar-bin/lib/sigar.jar:. ProcessState $$
bash: Sleeping

State of emacs editor used to write the example:
% java -classpath sigar-bin/lib/sigar.jar:. ProcessState 2673
emacs: Suspended

See also: examples/Ps.java, examples/Top.java

*/

public class ProcessState {

    private static String getStateString(char state) {
        switch (state) {
          case ProcState.SLEEP:
            return "Sleeping";
          case ProcState.RUN:
            return "Running";
          case ProcState.STOP:
            return "Suspended";
          case ProcState.ZOMBIE:
            return "Zombie";
          case ProcState.IDLE:
            return "Idle";
          default:
            return String.valueOf(state);
        }
    }

    public static void main(String[] args)
        throws SigarException {

        String pid;
        if (args.length == 0) {
            pid = "$$"; //default to this process
        }
        else {
            pid = args[0];
        }
		
		
		Sigar sigar = new Sigar();

try {
        

        ProcState procState = sigar.getProcState(pid);
        String state;

        System.out.println(procState.getName() + ": " +
                           getStateString(procState.getState()));
		
		Cpu cpu = sigar.getCpu();
		String cpuUsage = CpuPerc.format(cpu.getSys());
		System.out.println("CpuUsage: " + cpuUsage);


		//获得cpu信息，包括：CPU型号、CPU核心数、CPU版本、CPU主频
		CpuInfo[] infos = sigar.getCpuInfoList();
		
		CpuInfo cpuInfo = infos[0];
												
		String cpuModel = cpuInfo.getModel();
		System.out.println("CpuModel: " + cpuModel);
		
		int cpuTotalCore = cpuInfo.getTotalCores();
		System.out.println("cpuTotalCore: " + cpuModel);	
		String cpuVendo = cpuInfo.getVendor();
		System.out.println("cpuVendo: " + cpuVendo);	
		int cpuMhz = cpuInfo.getMhz();
		System.out.println("cpuMhz: " + cpuMhz);	
		
		String rxbps = "0";
		String txbps = "0";

		String[] netInterfaceList = sigar.getNetInterfaceList();
		System.out.println("net card: no" + netInterfaceList.length+ "  第一个网卡名：" + netInterfaceList[0]);
		for (int i = 0; i < netInterfaceList.length; i++) {
			String netInterface = netInterfaceList[i];
			if("eno1".equals(netInterface)){
				long start = System.currentTimeMillis();  
				NetInterfaceStat statStart = sigar.getNetInterfaceStat(netInterface);
				long rxBytesStart = statStart.getRxBytes();
				long txBytesStart = statStart.getTxBytes();
				Thread.sleep(2000);
				long end = System.currentTimeMillis();
				NetInterfaceStat statEnd = sigar.getNetInterfaceStat(netInterface);
				long rxBytesEnd = statEnd.getRxBytes();
				long txBytesEnd = statEnd.getTxBytes();
				
				//耗时（秒）
				long haoshi = (end-start)/1000;
				
				DecimalFormat df = new DecimalFormat("##0.0000");
				
				//上传速率 MB/s 保留3位小数
				rxbps = df.format((rxBytesEnd - rxBytesStart)/1024d/1024d/haoshi);
				
				//下载速率 MB/s  保留3位小数
				txbps = df.format((txBytesEnd - txBytesStart)/1024d/1024d/haoshi);
				break;
			}
		}
		System.out.println("rxbps:" + rxbps + "  txbps:" + txbps);

		
		//查询硬盘信息
		FileSystem fslist[] = sigar.getFileSystemList();

		//硬盘总大小
		int hardDiskTotal = 0;
		
		//硬盘已用大小
		int hardDiskRemain = 0;
		
		//内存总大小(单位/M)
		int memoryTotal = 0;
		
		//内存已用大小(单位/M)
		int memRemain = 0;


		for (int i = 0; i < fslist.length - 2; i++)

		{

			//System.out.println("============硬盘描述============");

			//System.out.println("\n~~~~~~~~~~" + i + "~~~~~~~~~~");

			FileSystem fs = fslist[i];

			// 分区的盘符名称

			//System.out.println("fs.getDevName() = " + fs.getDevName());

			// 分区的盘符名称

			//System.out.println("fs.getDirName() = " + fs.getDirName());

			// 文件系统类型，比如 FAT32、NTFS

			//System.out.println("fs.getSysTypeName() = " + fs.getSysTypeName());

			// 文件系统类型名，比如本地硬盘、光驱、网络文件系统等

			//System.out.println("fs.getTypeName() = " + fs.getTypeName());
			
			// 文件系统类型

			FileSystemUsage usage = sigar.getFileSystemUsage(fs.getDirName());
			
			if(fs.getDevName().equals("/dev/sdb1")){
				//硬盘总大小
				hardDiskTotal = (int) (usage.getTotal() / 1024 / 1024);
				
				
				hardDiskRemain = (int) (usage.getUsed() / 1024 / 1024);
				
				break;
			}
			
			
			String sub = fs.getDevName().substring(0, 1);

			// 文件系统总大小

			/*System.out.println(" 硬盘 " + sub + "=" + usage.getTotal() / 1024

			/ 1024 + "GB");*/

			// 文件系统剩余大小

			/*System.out.println(" 硬盘剩余大小= " + usage.getFree() / 1024 / 1024

			+ "GB");*/

			// 文件系统可用大小

			/*System.out.println(" 硬盘可用大小 = " + usage.getAvail() / 1024 / 1024

			+ "GB");*/
			
		}
		System.out.println("harddisktotal:"+hardDiskTotal+"    hardDiskRemain:"+hardDiskRemain);
		
		//查询内存信息
		Mem mem = sigar.getMem();
		memoryTotal = (int) (mem.getTotal()/1024/1024);
		memRemain = (int) (mem.getActualUsed()/1024/1024);
		/*System.out.println("free="+mem.getFree());
		System.out.println("free百分比="+mem.getFreePercent());
		System.out.println("actualFree="+mem.getActualFree());
		System.out.println("actualUsed="+mem.getActualUsed());*/
		
		System.out.println("memtotal="+memoryTotal+"    memRemain="+memRemain);

		} catch (Exception e) {
			System.out.println("Exception " );
			e.printStackTrace();
		}finally{
			sigar.close();
		}

    }
}
